#include "server.h"

// 全局原子变量：控制Python线程是否运行（如果脚本是长期任务）
std::atomic<bool> g_python_threads_running{ true };

void run_media_python() {
    std::println("media线程：开始执行");

    if (!Py_IsInitialized()) {
        std::println(std::cerr, "media线程：Python未初始化，退出");
        return;
    }

    try {
        FILE* fp = fopen("media.py", "r");
        if (!fp) {
            std::println(std::cerr, "media线程：无法打开media.py(错误: {})", strerror(errno));
            return;
        }
        
        std::println("media线程：开始运行media.py");
        PyGILState_STATE gstate = PyGILState_Ensure();  // 获取GIL

        // 执行Python脚本，并捕获错误
        int result = PyRun_SimpleFile(fp, "media.py");
        if (result != 0) {
            std::println(std::cerr, "media线程：media.py执行出错 (返回值{})", result);
            // 可选：打印Python错误信息
            PyErr_Print();
        }
        else {
            std::println("media线程：media.py执行完成");
        }

        PyGILState_Release(gstate);  // 释放GIL
        fclose(fp);
    }
    catch (...) {
        std::println("media线程：捕获未知异常");
    }

    std::println("media线程：退出");
}

void run_transmission_client(const std::string& config_path) {
    std::println("transmission线程：开始执行(配置路径: {})", config_path);

    if (!Py_IsInitialized()) {
        std::println(std::cerr, "transmission线程：Python未初始化，退出");
        return;
    }

    try {
        PyGILState_STATE gstate = PyGILState_Ensure();  // 获取GIL

        FILE* fp = fopen("transmission.py", "r");
        if (!fp) {
            std::println("transmission线程：无法打开transmission.py (错误: {})", strerror(errno));
            PyGILState_Release(gstate);  // 释放GIL后退出
            return;
        }
        std::println("transmission线程：开始运行transmission.py");
        // 执行Python脚本，并捕获错误
        int result = PyRun_SimpleFile(fp, "transmission.py");
        if (result != 0) {
            std::println(std::cerr, "transmission线程：transmission.py执行出错 (返回值: {})", result);
            PyErr_Print();  // 打印Python错误
        }
        else {
            std::println("transmission线程：transmission.py执行完成");
        }

        fclose(fp);
        PyGILState_Release(gstate);  // 释放GIL
    }
    catch (...) {
        std::println(std::cerr, "transmission线程：捕获未知异常");
    }

    std::println("transmission线程：退出");
}

std::string SensorHTTPServer::parse_http_request(const std::string& request) {
    size_t method_end = request.find(' ');
    if (method_end == std::string::npos) {
        return "";
    }

    size_t path_end = request.find(' ', method_end + 1);
    if (path_end == std::string::npos) {
        return "";
    }

    return request.substr(method_end + 1, path_end - method_end - 1);
}

std::string SensorHTTPServer::create_http_response(int status_code, const std::string& content, const std::string& content_type) {
    std::string status_str;
    switch (status_code) {
    case 200: status_str = "OK"; break;
    case 400: status_str = "Bad Request"; break;
    case 404: status_str = "Not Found"; break;
    case 500: status_str = "Internal Server Error"; break;
    default: status_str = "Unknown";
    }

    std::string response = "HTTP/1.1 " + std::to_string(status_code) + " " + status_str + "\r\n";
    response += "Content-Type: " + content_type + "\r\n";
    response += "Content-Length: " + std::to_string(content.size()) + "\r\n";
    response += "Connection: close\r\n";
    response += "\r\n";
    response += content;

    return response;
}

void SensorHTTPServer::pipe_listener()
{
    char buffer[BUFFER_SIZE];
    DWORD bytes_read;

    while (pipe_running) {
        // 读取Python发送的消息
        if (!ReadFile(
            hPipe,
            buffer,
            BUFFER_SIZE - 1,
            &bytes_read,
            NULL
        )) {
            DWORD err = GetLastError();
            if (err == ERROR_BROKEN_PIPE) {
                log("Python管道连接断开");
                break;
            }
            log("管道读取失败，错误码: " + std::to_string(err));
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            continue;
        }

        if (bytes_read > 0) {
            buffer[bytes_read] = '\0';
            log("[收到Python消息]: " + std::string(buffer));
            // 处理Python消息（例如更新传感器状态）
            handle_python_message(std::string(buffer));
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
}

void SensorHTTPServer::handle_python_message(const std::string& msg)
{
    try {
        nlohmann::json json_msg = nlohmann::json::parse(msg);
        std::string type = json_msg["type"];

        if (type == "sensor_status") {
            // 示例：更新传感器状态
            std::string sensor_name = json_msg["name"];
            bool status = json_msg["status"];
            log("传感器状态更新: " + sensor_name + " -> " + (status ? "运行中" : "已停止"));
        }
        else if (type == "query_result") {
            // 缓存Modbus查询结果
            std::lock_guard<std::mutex> lock(modbus_query_mutex);
            modbus_query_result = json_msg;
            log("已缓存Modbus查询结果: " + json_msg.dump());
        }
        else if (type == "error") {
            log("Python错误: " + json_msg["msg"].get<std::string>());
        }
    }
    catch (const std::exception& e) {
        log("解析Python消息失败: " + std::string(e.what()));
    }
}

bool SensorHTTPServer::start_python_client(const std::string& script_path)
{
    STARTUPINFO si = { sizeof(si) };
    PROCESS_INFORMATION pi;

    // 构建启动命令（确保python.exe在PATH中，或使用绝对路径）
    std::wstring cmd = L"python.exe " + std::wstring(script_path.begin(), script_path.end());

    if (!CreateProcess(
        NULL,                   // 不指定可执行文件路径
        &cmd[0],                // 命令行参数
        NULL, NULL,             // 安全属性
        FALSE,                  // 不继承句柄
        0,                      // 无特殊标志
        NULL, NULL,             // 环境变量和工作目录
        &si, &pi
    )) {
        log("启动Python失败，错误码: " + std::to_string(GetLastError()));
        return false;
    }

    // 关闭进程句柄（无需等待，管道断开时会处理）
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    return true;
}

std::string SensorHTTPServer::handle_http_request(const std::string& path, const std::string& body) {
    nlohmann::json response;

    // 处理不同的API路径
    if (path == "/connect") {
        sensor_collection.connect();
        response["status"] = "success";
        response["msg"] = "传感器连接完成";
        response["connected_sensors"] = sensor_collection.get_enabled_sensors();
    }
    else if (path == "/start") {
        int interval_ms = 100;
        try {
            if (!body.empty()) {
                nlohmann::json req = nlohmann::json::parse(body);
                if (req.contains("interval_ms")) {
                    interval_ms = req["interval_ms"];
                }
            }
        }
        catch (...) {
            // 忽略解析错误，使用默认值
        }

        sensor_collection.start_mm_timer(interval_ms);
        response["status"] = "success";
        response["msg"] = "定时器启动（间隔：" + std::to_string(interval_ms) + "ms）";
    }
    else if (path == "/stop") {
        sensor_collection.stop_mm_timer();
        response["status"] = "success";
        response["msg"] = "定时器已停止";
    }
    else if (path == "/status") {
        response["status"] = "success";
        response["is_timer_running"] = sensor_collection.is_timer_running();
        response["connected_sensors"] = sensor_collection.get_enabled_sensors();
    }
    else if (path == "/media/status") {
        // 可以通过Python C API获取media状态
        response["status"] = "success";
        response["media_status"] = "running";  // 简化处理，实际应调用media模块接口
    }
    else if (path == "/transmission/evaluate") {
        // 向Python发送评估指令
        nlohmann::json cmd;
        cmd["type"] = "evaluate";
        std::string cmd_str = cmd.dump();

        send_to_transmission(cmd_str);  // 复用现有发送管道的方法

        response["status"] = "success";
        response["msg"] = "已触发数据评估，正在处理...";
        log("触发Transmission数据评估");
        return create_http_response(200, response.dump());
    }
    else if (path == "/transmission/evaluate/status") {
        std::lock_guard<std::mutex> lock(eval_status_mutex);
        response["status"] = "success";
        response["done"] = eval_status.done;
        response["has_3d"] = eval_status.has_3d;
        response["has_slices"] = eval_status.has_slices;
        log("查询Transmission评估状态");
        return create_http_response(200, response.dump());
    }
    else if (path == "/transmission/data/3d") {
        std::lock_guard<std::mutex> lock(cached_3d_mutex);
        if (cached_3d_data.empty()) {
            response["status"] = "error";
            response["msg"] = "3D数据未生成或未缓存";
            return create_http_response(404, response.dump());
        }
        response["status"] = "success";
        response["data"] = cached_3d_data;
        log("请求获取3D数据");
        return create_http_response(200, response.dump());
    }
    else if (path == "/transmission/data/slices") {
        std::lock_guard<std::mutex> lock(cached_slices_mutex);
        if (cached_slices_data.empty()) {
            response["status"] = "error";
            response["msg"] = "切片数据未生成或未缓存";
            return create_http_response(404, response.dump());
        }
        response["status"] = "success";
        response["count"] = cached_slices_data.size();
        response["data"] = cached_slices_data;
        log("请求获取切片数据");
        return create_http_response(200, response.dump());
    }
    else if (path == "/transmission/reset") {
        {
            std::lock_guard<std::mutex> lock(eval_status_mutex);
            eval_status = EvaluateStatus();  // 重置为初始状态
        }
        {
            std::lock_guard<std::mutex> lock(cached_3d_mutex);
            cached_3d_data.clear();
        }
        {
            std::lock_guard<std::mutex> lock(cached_slices_mutex);
            cached_slices_data.clear();
        }
        response["status"] = "success";
        response["msg"] = "评估状态已重置";
        log("重置Transmission评估状态");
        return create_http_response(200, response.dump());
    }
    else if (path == "/frame") {
        log("收到Media视频帧数据（大小: " + std::to_string(body.size()) + "字节）");  // 终端日志

        // 简单处理：直接返回成功（前端可通过该接口获取实时帧）
        response["status"] = "success";
        response["msg"] = "帧数据已接收";
        return create_http_response(200, response.dump());
    }
    else if (path == "/modbus/control") {
        log("收到Modbus设备控制请求");  // 终端日志
        try {
            if (body.empty()) {
                throw std::invalid_argument("请求体为空");
            }
            nlohmann::json req = nlohmann::json::parse(body);

            // 校验必填参数
            if (!req.contains("control_type") || !req.contains("data")) {
                throw std::invalid_argument("缺少control_type或data参数");
            }

            // 构造转发给Python的指令
            nlohmann::json cmd;
            cmd["type"] = "control";
            cmd["control_type"] = req["control_type"];
            cmd["data"] = req["data"];

            // 通过管道发送给modbus.py
            send_to_python(cmd.dump());

            response["status"] = "success";
            response["msg"] = "控制指令已转发给设备";
            return create_http_response(200, response.dump());
        }
        catch (const std::exception& e) {
            response["status"] = "error";
            response["msg"] = e.what();
            return create_http_response(400, response.dump());
        }
    }
    else if (path == "/modbus/query") {
        log("收到Modbus设备状态查询请求");  // 终端日志
        try {
            if (body.empty()) {
                throw std::invalid_argument("请求体为空");
            }
            nlohmann::json req = nlohmann::json::parse(body);

            // 校验必填参数
            if (!req.contains("query_type") || !req.contains("name") || !req.contains("action")) {
                throw std::invalid_argument("缺少query_type、name或action参数");
            }

            // 构造转发给Python的指令
            nlohmann::json cmd;
            cmd["type"] = "query";
            cmd["query_type"] = req["query_type"];
            cmd["name"] = req["name"];
            cmd["action"] = req["action"];

            // 发送前清空旧结果
            {
                std::lock_guard<std::mutex> lock(modbus_query_mutex);
                modbus_query_result.clear();
            }

            // 通过管道发送给modbus.py
            send_to_python(cmd.dump());

            response["status"] = "success";
            response["msg"] = "查询指令已发送，可通过/modbus/query/result获取结果";
            return create_http_response(200, response.dump());
        }
        catch (const std::exception& e) {
            response["status"] = "error";
            response["msg"] = e.what();
            return create_http_response(400, response.dump());
        }
     }
    else if (path == "/modbus/query/result") {
        log("收到Modbus查询结果请求");  // 终端日志
        std::lock_guard<std::mutex> lock(modbus_query_mutex);

        if (modbus_query_result.empty()) {
            response["status"] = "pending";
            response["msg"] = "查询结果未返回，请稍后重试";
            return create_http_response(202, response.dump());  // 202表示请求已接收但未完成
        }

        response["status"] = "success";
        response["data"] = modbus_query_result;
        return create_http_response(200, response.dump());
        }
    else {
        response["status"] = "error";
        response["msg"] = "未知路径: " + path;
        return create_http_response(404, response.dump());
    }

    return create_http_response(200, response.dump());
}

void SensorHTTPServer::handle_client(boost::asio::ip::tcp::socket& client) {
    std::string ip = client.remote_endpoint().address().to_string();
    log("客户端已连接：" + ip);

    try {
        boost::asio::streambuf buf;
        boost::system::error_code ec;

        // 读取请求
        boost::asio::read_until(client, buf, "\r\n\r\n", ec);
        if (ec) {
            log("读取请求失败：" + ec.message());
            return;
        }

        // 解析请求
        std::string request_str((std::istreambuf_iterator<char>(&buf)), std::istreambuf_iterator<char>());
        std::string path = parse_http_request(request_str);

        // 提取请求体
        size_t body_pos = request_str.find("\r\n\r\n");
        std::string body;
        if (body_pos != std::string::npos) {
            body = request_str.substr(body_pos + 4);
        }

        log("收到请求: " + path);

        // 处理请求并生成响应
        std::string response = handle_http_request(path, body);

        // 发送响应
        boost::asio::write(client, boost::asio::buffer(response), ec);
        if (ec) {
            log("发送响应失败：" + ec.message());
        }
        else {
            log("响应已发送: " + path);
        }
    }
    catch (const std::exception& e) {
        log("客户端处理异常：" + std::string(e.what()));
    }

    client.close();
}

void SensorHTTPServer::load_config(const std::string& config_path) {
    host = "127.0.0.1";
    port = 8888;

    try {
        YAML::Node config = YAML::LoadFile(config_path);
        if (config["host"]) {
            host = config["host"].as<std::string>();
            log("从配置文件加载host: " + host);
        }
        if (config["port"]) {
            port = config["port"].as<uint16_t>();
            log("从配置文件加载port: " + std::to_string(port));
        }
    }
    catch (const std::exception& e) {
        log("加载配置失败（" + std::string(e.what()) + "），使用默认配置: host=" + host + ", port=" + std::to_string(port));
    }
}

//void SensorHTTPServer::start_python_threads() {
//    // 启动TransmissionClient线程
//    std::string transmission_config = "./configs/transmission.yaml";
//    transmission_thread = std::thread(run_transmission_client, transmission_config);
//    // 检查线程是否可连接（若可连接，说明创建成功）
//    std::println("transmission_thread 创建成功，已启动");
//
//
//    // 启动media.py线程
//    media_thread = std::thread(run_media_python);
//}

void SensorHTTPServer::start_python_threads() {
    // 启动TransmissionClient线程（带配置路径参数）
    std::string transmission_config = "./configs/transmission.yaml";
    transmission_thread = std::thread([this, transmission_config]() {
        // 启动Python脚本
        if (!Py_IsInitialized()) {
            log("Python未初始化(transmission)");
            return;
        }

        PyGILState_STATE gstate = PyGILState_Ensure();
        // 构造命令行参数（传递配置文件路径）
        std::wstring cmd = L"python.exe transmission.py " + std::wstring(transmission_config.begin(), transmission_config.end());
        FILE* fp = _wpopen(cmd.c_str(), L"r");  // 使用带参数的方式启动
        if (!fp) {
            log("无法启动transmission.py，错误: " + std::string(strerror(errno)));
            PyGILState_Release(gstate);
            return;
        }

        // 等待脚本启动并连接管道
        std::this_thread::sleep_for(std::chrono::seconds(1));
        // 初始化Transmission管道
        this->init_transmission_pipe();

        // 阻塞等待脚本执行完成
        int result = _pclose(fp);
        if (result != 0) {
            log("transmission.py执行出错，返回值: " + std::to_string(result));
        }
        PyGILState_Release(gstate);
        });

    // 启动media.py线程（保持不变）
    media_thread = std::thread(run_media_python);
}

void SensorHTTPServer::start() {
    try {
        boost::asio::io_context io_context;
        boost::asio::ip::address server_addr;

        try {
            server_addr = boost::asio::ip::make_address(host);
        }
        catch (const boost::system::system_error& e) {
            log("无效的IP地址（" + host + "）：" + e.what() + "，使用默认地址127.0.0.1");
            server_addr = boost::asio::ip::make_address("127.0.0.1");
        }

        acceptor = new boost::asio::ip::tcp::acceptor(
            io_context,
            boost::asio::ip::tcp::endpoint(server_addr, port)
        );

        log("HTTP服务端启动，监听 " + host + ":" + std::to_string(port));

        while (is_running) {
            boost::asio::ip::tcp::socket client(io_context);
            boost::system::error_code ec;
            acceptor->accept(client, ec);

            if (ec) {
                if (is_running) {
                    log("接受连接失败：" + ec.message());
                }
                continue;
            }

            handle_client(client);
        }
    }
    catch (const std::exception& e) {
        if (is_running) {
            log("服务端异常：" + std::string(e.what()));
        }
    }
    log("服务端已停止");
}

void SensorHTTPServer::stop() {
    is_running = false;
    log("服务端开始停止...");

    if (acceptor != nullptr) {
        boost::system::error_code ec;
        acceptor->close(ec);
        if (ec) {
            log("关闭acceptor失败：" + ec.message());
        }
        else {
            log("acceptor已关闭");
        }
    }

    sensor_collection.stop_mm_timer();
    log("传感器定时器已停止");
}

void SensorHTTPServer::send_to_python(const std::string& data)
{
    if (hPipe == INVALID_HANDLE_VALUE || !pipe_running) {
        log("管道未连接，发送失败");
        return;
    }

    std::lock_guard<std::mutex> lock(pipe_mutex);
    std::string send_data = data + "\r\n";  // 换行符作为消息分隔符
    DWORD bytes_written;

    if (!WriteFile(
        hPipe,
        send_data.c_str(),
        send_data.size(),
        &bytes_written,
        NULL
    )) {
        log("发送到Python失败，错误码: " + std::to_string(GetLastError()));
    }
    else {
        log("[发送到Python]: " + data);
    }
}

bool SensorHTTPServer::init_pipe_communication(const std::string& python_script)
{
    // 创建命名管道（服务端）
    hPipe = CreateNamedPipe(
        PIPE_NAME,
        PIPE_ACCESS_DUPLEX,        // 双向通信
        PIPE_TYPE_MESSAGE |        // 消息模式
        PIPE_READMODE_MESSAGE |
        PIPE_WAIT,                 // 阻塞模式
        1,                         // 最大实例数
        BUFFER_SIZE,               // 输出缓冲区
        BUFFER_SIZE,               // 输入缓冲区
        5000,                      // 超时时间（5秒）
        NULL                       // 默认安全属性
    );

    if (hPipe == INVALID_HANDLE_VALUE) {
        log("创建管道失败，错误码: " + std::to_string(GetLastError()));
        return false;
    }

    // 启动Python客户端脚本
    if (!start_python_client(python_script)) {
        CloseHandle(hPipe);
        hPipe = INVALID_HANDLE_VALUE;
        return false;
    }

    // 等待Python连接管道
    log("等待Python连接管道...");
    if (!ConnectNamedPipe(hPipe, NULL) && GetLastError() != ERROR_PIPE_CONNECTED) {
        log("管道连接失败，错误码: " + std::to_string(GetLastError()));
        CloseHandle(hPipe);
        hPipe = INVALID_HANDLE_VALUE;
        return false;
    }

    // 启动监听线程
    pipe_running = true;
    pipe_listener_thread = std::thread(&SensorHTTPServer::pipe_listener, this);
    log("管道通信初始化完成");
    return true;
}

void SensorHTTPServer::close_pipe_communication()
{
    pipe_running = false;
    if (pipe_listener_thread.joinable()) {
        pipe_listener_thread.join();
    }
    if (hPipe != INVALID_HANDLE_VALUE) {
        DisconnectNamedPipe(hPipe);
        CloseHandle(hPipe);
        hPipe = INVALID_HANDLE_VALUE;
    }
    log("管道通信已关闭");
}

bool SensorHTTPServer::init_transmission_pipe()
{
    hTransmissionPipe = CreateNamedPipe(
        TRANSMISSION_PIPE_NAME,
        PIPE_ACCESS_DUPLEX,
        PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
        1,
        BUFFER_SIZE,
        BUFFER_SIZE,
        5000,
        NULL
    );

    if (hTransmissionPipe == INVALID_HANDLE_VALUE) {
        log("创建Transmission管道失败，错误码: " + std::to_string(GetLastError()));
        return false;
    }

    // 启动Transmission客户端后再连接管道
    log("等待Transmission连接管道...");
    if (!ConnectNamedPipe(hTransmissionPipe, NULL) && GetLastError() != ERROR_PIPE_CONNECTED) {
        log("Transmission管道连接失败，错误码: " + std::to_string(GetLastError()));
        CloseHandle(hTransmissionPipe);
        hTransmissionPipe = INVALID_HANDLE_VALUE;
        return false;
    }

    transmission_pipe_running = true;
    transmission_pipe_thread = std::thread(&SensorHTTPServer::transmission_pipe_listener, this);
    log("Transmission管道初始化完成");
    return true;
}

void SensorHTTPServer::close_transmission_pipe()
{
    transmission_pipe_running = false;
    if (transmission_pipe_thread.joinable()) {
        transmission_pipe_thread.join();
    }
    if (hTransmissionPipe != INVALID_HANDLE_VALUE) {
        DisconnectNamedPipe(hTransmissionPipe);
        CloseHandle(hTransmissionPipe);
        hTransmissionPipe = INVALID_HANDLE_VALUE;
    }
    log("Transmission管道已关闭");
}

void SensorHTTPServer::transmission_pipe_listener()
{
    char buffer[BUFFER_SIZE];
    DWORD bytes_read;

    while (transmission_pipe_running) {
        if (!ReadFile(
            hTransmissionPipe,
            buffer,
            BUFFER_SIZE - 1,
            &bytes_read,
            NULL
        )) {
            DWORD err = GetLastError();
            if (err == ERROR_BROKEN_PIPE) {
                log("Transmission管道连接断开");
                break;
            }
            log("Transmission管道读取失败，错误码: " + std::to_string(err));
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            continue;
        }

        if (bytes_read > 0) {
            buffer[bytes_read] = '\0';
            log("[收到Transmission消息]: " + std::string(buffer));
            handle_transmission_message(std::string(buffer));
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
}

void SensorHTTPServer::handle_transmission_message(const std::string& msg)
{
    try {
        nlohmann::json json_msg = nlohmann::json::parse(msg);
        std::string type = json_msg["type"];

        if (type == "evaluate_done") {
            std::lock_guard<std::mutex> lock(eval_status_mutex);
            eval_status.done = true;
            eval_status.has_3d = json_msg["has_3d"];
            eval_status.has_slices = json_msg["has_slices"];
            log("数据评估完成，3D数据: " + std::string(eval_status.has_3d ? "存在" : "不存在"));
        }
        else if (type == "3d_data") {
            std::lock_guard<std::mutex> lock(cached_3d_mutex);
            cached_3d_data = json_msg["data"];  // 缓存3D数据
            log("已缓存3D数据，体素数量: " + std::to_string(cached_3d_data["value"].size()));
        }
        else if (type == "slices_data") {
            std::lock_guard<std::mutex> lock(cached_slices_mutex);
            cached_slices_data = json_msg["data"];  // 缓存切片数据
            log("已缓存切片数据，数量: " + std::to_string(cached_slices_data.size()));
        }
        else if (type == "error") {
            log("Transmission错误: " + json_msg["msg"].get<std::string>());
        }
    }
    catch (const std::exception& e) {
        log("解析Transmission消息失败: " + std::string(e.what()));
    }
}

void SensorHTTPServer::send_to_transmission(const std::string& data)
{
    if (hTransmissionPipe == INVALID_HANDLE_VALUE || !transmission_pipe_running) {
        log("Transmission管道未连接，发送失败");
        return;
    }

    std::lock_guard<std::mutex> lock(transmission_pipe_mutex);
    std::string send_data = data + "\r\n";
    DWORD bytes_written;

    if (!WriteFile(
        hTransmissionPipe,
        send_data.c_str(),
        send_data.size(),
        &bytes_written,
        NULL
    )) {
        log("发送到Transmission失败，错误码: " + std::to_string(GetLastError()));
    }
    else {
        log("[发送到Transmission]: " + data);
    }
}
